<template>
  <div>
    <!-- label-width:表单域标签的宽度，作为 Form 直接子元素的 form-item 会继承该值 -->
    <el-form ref="form" label-width="80px" :model="spu">
      <el-form-item label="SPU名称">
        <el-input placeholder="SPU名称" v-model="spu.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="spu.tmId">
          <el-option
            :label="tm.tmName"
            :value="tm.id"
            v-for="tm in tradeMarkList"
            :key="tm.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          type="textarea"
          rows="4"
          placeholder="SPU描述"
          v-model="spu.description"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <!-- action:图片上传地址 list-type:文件列表的类型  file-list:上传的文件列表(数组类型，必须有name和url) -->
        <!-- on-preview:文件预览时会触发  on-remove:当删除图片的时候会触发  on-success：文件上传成功时会触发 -->
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :file-list="spuImageList"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handlerSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" size="tiny">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select
          :placeholder="`还有${unSelectSaleAttr.length}未选择`"
          v-model="attrIdAndAttrName"
        >
          <el-option
            :label="unselect.name"
            :value="`${unselect.id}:${unselect.name}`"
            v-for="unselect in unSelectSaleAttr"
            :key="unselect.id"
          >
          </el-option>
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-plus"
          style="margin-left: 10px"
          :disabled="!attrIdAndAttrName"
          @click="addSaleAttr"
          >添加销售属性</el-button
        >
        <!-- 展示的是当前spu属于自己的销售属性 -->
        <el-table
          style="width: 100%; margin-top: 20px"
          border
          :data="spu.spuSaleAttrList"
        >
          <el-table-column
            type="index"
            label="序号"
            width="80px"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="saleAttrName"
            label="属性名"
            width="width"
          ></el-table-column>
          <el-table-column prop="prop" label="属性值名称列表" width="width">
            <template slot-scope="{ row }">
              <el-tag
                :key="tag.id"
                v-for="(tag, index) in row.spuSaleAttrValueList"
                closable
                :disable-transitions="false"
                @close="row.spuSaleAttrValueList.splice(index, 1)"
              >
                {{ tag.saleAttrValueName }}
              </el-tag>
              <!-- @keyup.enter.native="handleInputConfirm"
                 -->
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.inputValue"
                ref="saveTagInput"
                size="small"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <!-- @click="showInput" -->
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="addSaleAttrValue(row)"
                >添加</el-button
              >
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{ $index }">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="spu.spuSaleAttrList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOrUpdateSpu">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "SpuForm",
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      // spu属性初始化时是一个空对象，修改spu时会向服务器发送请求，返回spu信息（对象）
      // 添加spu时并没有向服务器发送请求，数据收集到spu，有哪些字段需要看文档
      spu: {
        // 三级分类的id
        category3Id: 0,
        tmId: "", //品牌id
        description: "", // 描述
        spuName: "",
        spuImageList: [
          /* {
             id: 0,
            imgName: "",
            imgUrl: "",
            spuId: 0, 
          }, */
        ],
        spuSaleAttrList: [
          /* {
            baseSaleAttrId: 0,
            id: 0,
            saleAttrName: "",
            spuId: 0,
            spuSaleAttrValueList: [
              {
                baseSaleAttrId: 0,
                id: 0,
                isChecked: "",
                saleAttrName: "",
                saleAttrValueName: "",
                spuId: 0,
              },
            ],
          }, */
        ],
      }, //存储某一个spu的信息
      tradeMarkList: [], //存储品牌信息
      spuImageList: [], //存储spu图片的数据
      saleAttrList: [], //销售属性的数据
      attrIdAndAttrName: "", //收集未选择的销售属性的id
    };
  },
  methods: {
    // 图片删除时的回调---需要收集数据
    handleRemove(file, fileList) {
      // file：删除的那张图片  fileList：删除后剩余的其他图片
      // console.log(file, fileList);
      // 收集照片墙图片的数据,照片墙中的数据有name和url字段，但是对于服务器而言不需要，所以暂时存于spuImageList
      this.spuImageList = fileList;
    },
    // 图片预览的回调
    handlePictureCardPreview(file) {
      // 图片地址赋值给dialogImageUrl这个属性
      this.dialogImageUrl = file.url;
      // 控制对话框的显示
      this.dialogVisible = true;
    },
    // 照片墙图片上传成功的回调---需要收集数据
    handlerSuccess(response, file, fileList) {
      this.spuImageList = fileList;
    },
    // 点击修改spu按钮时初始化spuform数据
    async initSpuData(spu) {
      console.log("发请求");
      // 获取某一个spu信息
      let spuResult = await this.$API.spu.reqSpu(spu.id);
      console.log(spuResult, "获取某一个spu信息");
      if (spuResult.code == 200) {
        this.spu = spuResult.data;
      }
      // 获取品牌数据
      let trademarkResult = await this.$API.spu.reqTrademarkList();
      console.log(trademarkResult, "获取品牌数据");
      if (trademarkResult.code == 200) {
        this.tradeMarkList = trademarkResult.data;
      }
      // 获取spu图片
      let spuImageResult = await this.$API.spu.reqSpuImageList(spu.id);
      console.log(spuImageResult, "获取spu图片");
      if (spuImageResult.code == 200) {
        let listArr = spuImageResult.data;
        // 照片墙显示的图片数组需要有name和url字段
        listArr.forEach((item) => {
          item.name = item.imgName;
          item.url = item.imgUrl;
        });
        this.spuImageList = listArr;
      }
      // 获取平台全部销售属性
      let saleResult = await this.$API.spu.reqBaseSaleAttrList();
      console.log(saleResult, "获取平台全部销售属性");
      if (saleResult.code == 200) {
        this.saleAttrList = saleResult.data;
      }
    },
    // 添加新的销售属性
    addSaleAttr() {
      // 把收集到的销售属性数据进行分割
      const [baseSaleAttrId, saleAttrName] = this.attrIdAndAttrName.split(":");
      // 向SPU对象的spuSaleAttrList属性里面添加新的销售属性
      let newSaleAttr = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: [],
      };
      // 添加新的销售属性
      this.spu.spuSaleAttrList.push(newSaleAttr);
      // 清空数据
      this.attrIdAndAttrName = "";
    },
    // 添加新的销售属性值按钮的回调
    addSaleAttrValue(row) {
      // inputVisible控制input和button的切换
      // 添加响应式属性inputVisible来控制状态切换，inputValue收集新增的属性值
      this.$set(row, "inputVisible", true);
      this.$set(row, "inputValue", "");
    },
    // el-input失去焦点的回调
    handleInputConfirm(row) {
      const { baseSaleAttrId, inputValue } = row;
      // 新增销售属性值不能重复、不能为空
      if (inputValue.trim() == "") {
        this.$message("属性值不能为空");
        return;
      }
      let result = row.spuSaleAttrValueList.every(
        (item) => item.saleAttrValueName != inputValue
      );
      if (!result) return;

      let newSaleAttrValue = { baseSaleAttrId, saleAttrValueName: inputValue };
      row.spuSaleAttrValueList.push(newSaleAttrValue);
      // inputVisible已经是响应式属性了，可以直接修改
      row.inputVisible = false;
    },
    // 保存按钮的回调
    async addOrUpdateSpu() {
      // 整理参数，需要整理照片墙的数据
      // 携带参数：对于图片，需要携带imageUrl和imageName字段
      this.spu.spuImageList = this.spuImageList.map((item) => {
        return {
          imageName: item.name,
          imageUrl: (item.response && item.response.data) || item.url,
        };
      });
      let result;
      //let save = this.$qs.stringify({'spu':this.spu});
      // 发请求
      try {
        result = await this.$API.spu.reqAddOrUpdateSpu(this.spu);
        console.log(result, "保存spu成功");
      } catch (error) {
        result = error;
        console.log(result, "保存spu失败");
      }
      if (result.code == 200) {
        this.$message({ type: "success", message: "保存成功" });
        // 通知父组件回到场景0
        this.$emit("changeScene", {
          scene: 0,
          flag: this.spu.id ? "修改" : "添加",
        });
      }
      Object.assign(this._data, this.$options.data()); //清除数据
    },

    // 点击添加spu按钮时发请求的回调
    async addSpuData(Id3) {
      console.log("添加");
      this.spu.category3Id = Id3; //收集三级分类的id
      // 获取品牌数据
      let trademarkResult = await this.$API.spu.reqTrademarkList();
      console.log(trademarkResult, "获取品牌数据");
      if (trademarkResult.code == 200) {
        this.tradeMarkList = trademarkResult.data;
      }
      // 获取平台全部销售属性
      let saleResult = await this.$API.spu.reqBaseSaleAttrList();
      console.log(saleResult, "获取平台全部销售属性");
      if (saleResult.code == 200) {
        this.saleAttrList = saleResult.data;
      }
    },
    // 取消按钮
    cancel() {
      this.$emit("changeScene", { scene: 0, flag: "" });
      Object.assign(this._data, this.$options.data()); //清除数据
    },
  },
  computed: {
    // 计算出还未选择的销售属性
    unSelectSaleAttr() {
      // 整个平台的销售属性有三个：颜色、版本、尺寸---saleAttrList
      // 当前spu拥有属于自己的销售属性spu.spuSaleAttrList
      return this.saleAttrList.filter((item) => {
        return this.spu.spuSaleAttrList.every((item1) => {
          return item.name != item1.saleAttrName;
        });
      });
    },
  },
};
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>